package com.rocky.pubimport.controller;

import com.rocky.pubimport.common.ImportInfo;
import com.rocky.pubimport.common.ResponseImportResult;
import com.rocky.pubimport.common.ResultData;
import com.rocky.pubimport.service.IPubImportRecordProcessService;
import com.rocky.pubimport.service.strategy.PubImportRecordProcessServiceStrategyHolder;
import com.rocky.pubimport.utils.JsonUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 控制层
 * @author rocky
 * @date 2022/5/7 9:41
 */
@RestController
@RequestMapping("/pub/import/record")
public class PubImportRecordController {

    @Resource
    public PubImportRecordProcessServiceStrategyHolder holder;

    @RequestMapping(value = "/downloadTemplate")
    @ResponseBody
    public void downloadTemplate(HttpServletResponse response, String model) throws IOException {
        IPubImportRecordProcessService service = holder.getStrategyService(model);
        if (service == null) {
            ResultData data = new ResultData();
            data.setStatus(-200);
            data.setMsg("业务模块[" + model + "]的数据导入功能暂未开放");
            response.setContentType("application/json");
            PrintWriter printWriter = response.getWriter();
            printWriter.write(JsonUtils.toJson(data));
            printWriter.flush();
            printWriter.close();
        }
        service.downloadTemplate(response);
    }

    @RequestMapping(value = "/importExcel")
    @ResponseBody
    public ResponseImportResult importExcel(ImportInfo importInfo) {
        ResponseImportResult result = new ResponseImportResult();
        IPubImportRecordProcessService service = holder.getStrategyService(importInfo.getModel());
        if (service == null) {
            result = ResponseImportResult.error("业务模块[" + importInfo.getModel() + "]的数据导入功能暂未开放");
            return result;
        }
        try {
            result = service.importExcel(importInfo);
        } catch(Exception ex) {
            result = ResponseImportResult.error("导入失败");
        }
        return result;
    }


}
